import { createStore } from "vuex";
import vuexPer from "vuex-persistedstate";
export default createStore({
  state: {
    shopcar: [],
    checked: false,
  },
  mutations: {
    add(state, obj) {
      let flag = false;
      state.shopcar.forEach((item) => {
        if (item.id == obj.id) {
          item.num++;
          flag = true;
        }
      });

      if (flag == false) {
        obj.num = 1;
        obj.status = false;
        state.shopcar.push(obj);
      }
    },
    //添加购物车
    changeItem(state) {
      state.checked = state.shopcar.every((item) => {
        return item.status == true;
      });
    },
    checkall(state) {
      state.shopcar.forEach((item) => {
        item.status = state.checked;
      });
    },
    //全选

    clear(state) {
      state.shopcar = state.shopcar.filter((item) => {
        return item.status == false;
      });
    },
    //选中删除
  },
  actions: {},
  modules: {},
  getters: {
    price(state) {
      let sum = 0;
      state.shopcar.forEach((item) => {
        if (item.status == true) {
          sum += item.num * item.minPrice;
        }
      });
      return sum;
    },
  },
  plugins: [vuexPer()],
});
